//
//  UIScrollView.swift
//  KastKing
//
//  Created by liujianlong on 2023/1/31.
//

import UIKit 
import MJRefresh
private var pageKey = "paramsKey"
private var updateBlockKey = "updateBlockKey"
public extension UIScrollView {
    var page : Int {
        get{
            objc_getAssociatedObject(self, &pageKey) as? Int ?? 1
        }
        set{
            objc_setAssociatedObject(self, &pageKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }
    
    var updateBlock:(()->Void)?{
        get{
            objc_getAssociatedObject(self, &updateBlockKey) as? ()->Void
        }set{
            objc_setAssociatedObject(self, &updateBlockKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    func setupRefreshing(){
        let header : MJRefreshNormalHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNew))
        header.setTitle("", for: .refreshing)
        self.mj_header = header
        
        let footer : MJRefreshAutoNormalFooter = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore))
        //        footer.setTitle("", for: .idle)
        footer.setTitle("加载更多数据", for: .refreshing)
        //        footer.setTitle("没有更多数据", for: .noMoreData)
        //        self.mj_footer = footer
    }
    
    func endRefreshing(){
        self.mj_header?.endRefreshing()
        self.mj_footer?.endRefreshing()
    }
    
    func setHeaderTitle(title:String, state:MJRefreshState){
        guard let header = self.mj_header as? MJRefreshStateHeader else{return}
        header.setTitle(title, for: state)
    }
    
    func setFooterTitle(title:String, state:MJRefreshState){
        guard let footer = self.mj_header as? MJRefreshAutoStateFooter else{return}
        footer.setTitle(title, for: state)
    }
    
    @objc private func loadNew(){
        self.page = 1
        self.updateBlock?()
    }
    
    @objc private func loadMore(){
        self.page += 1
        self.updateBlock?()
    }
}
